<template>
  <div class="modal-from">
    <a-modal
      title="编辑"
      :width="1000"
      style="top: 50px;"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="submit"
      @cancel="handleCancel"
    >
      <div class="v-form-title">客户资料</div>
      <a-row :gutter="24">
        <a-col :md="6" :sm="24" >
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="联系号码"
              :wrapperCol="wrapperCol"
            >
              <a-input
                disabled
                ref="phoneInput"
                style="width: 100%"
                placeholder="请输入联系号码"
                v-decorator="['customerContact.contactContent',{rules: [{ required: false, message: '请输入联系号码！' }]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="联系方式"
              :wrapperCol="wrapperCol"
            >
              <a-select  allow-clear style="width: 100%" v-decorator="['customerContact.contactType', {rules: [{ required: false, message: '请选择联系方式！' }]}]" :disabled="disabled" placeholder="请选择联系方式" >
                <a-select-option v-for="(item,index) in CustomerConsult.contactDetails"  :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="客户姓名"
              :wrapperCol="wrapperCol"
            >
              <a-input
                :disabled="disabled"
                ref="nameInput"
                placeholder="请输入客户姓名"
                style="width: 100%"
                v-decorator="['customer.name',{rules: [{ required: false, message: '请输入客户姓名！' }]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24" >
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="客户卡号"
              :wrapperCol="wrapperCol"
            >
              <a-input
                ref="cardNoInput"
                :disabled="true"
                v-decorator="['customer.cardNo']"
                placeholder="请输入客户卡号"
              />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item label="区域来源" :wrapperCol="wrapperCol">
              <a-cascader
                expand-trigger="hover"
                :disabled="disabled_area_source"
                :show-search="{ filter }"
                :options="area"
                v-decorator="['customer.areaId', {rules: [{ required: false, message: '请选择区域来源！' }]}]"
                placeholder="区域来源，可搜索"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="信息来源"
              :wrapperCol="wrapperCol"
            >
              <a-cascader
                allow-clear
                :disabled="disabled_info_source"
                :options="infoSource"
                expand-trigger="hover"
                :show-search="{ filter }"
                v-decorator="['customer.infoSource', {rules: [{ required: false, message: '请选择信息来源！' }]}]"
                placeholder="信息来源，可搜索"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="性别"
              :wrapperCol="wrapperCol"
            >
              <a-select
                allow-clear
                style="width: 100%"
                placeholder="请选择性别"
                :disabled="false"
                v-decorator="['customer.sex', {rules: [{ required: false, message: '请选择性别！' }]}]" >
                <a-select-option  v-for="(item,index) in sex" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>

        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="年龄"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                :disabled="false"
                placeholder="请填写年龄"
                v-decorator="['customer.age', {rules: [{ required: false, message: '请填写年龄！' },{validator: validatorAge}]}]" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">

        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item label="开发员" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                allow-clear
                style="width: 100%"
                placeholder="-"
                :disabled="true"
                v-model="customer_response.developerid">
                <a-select-option  v-for="(item,index) in userList" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>

        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item label="所属咨询" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                allow-clear
                style="width: 100%"
                placeholder="-"
                :disabled="true"
                v-model="customer_response.consult_man_id" >
                <a-select-option  v-for="(item,index) in userList" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>

      </a-row>
      <div class="v-form-title">咨询资料</div>
      <a-row :gutter="24" style="margin-top: 20px;">
        <a-col :span="6" >
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="客户诉求"
              :wrapperCol="wrapperCol"
              has-feedback>
              <a-select
                :disabled="disabled_zixun"
                :showSearch="true"
                option-filter-prop="children"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择客户诉求,可直接搜索"
                v-decorator="['quoteItemList', {rules: [{ required: true, message: '请选择项目！' }]}]"
                option-label-prop="label"
              >
                <a-select-option v-for="item in ConsultationAppeal" :key="item.id" :label="item.name" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24" >
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="咨询工具"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select
                :disabled="disabled_zixun"
                allow-clear
                style="width: 100%"
                placeholder="请选择咨询工具"
                v-decorator="['consultRecord.consultToolId', {rules: [{ required: false, message: '请选择咨询工具！' }]}]" >
                <a-select-option v-for="(item,index) in CustomerConsult.consultTools" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="来院意向"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select
                :disabled="disabled_zixun"
                allow-clear
                style="width: 100%"
                placeholder="请选择来院意向"
                v-decorator="['consultRecord.clientIntentionId', {rules: [{ required: false, message: '请选择消息来源！' }]}]" >
                <a-select-option v-for="(item,index) in CustomerConsult.comeHosStatus" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="来源地址"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                :disabled="disabled_zixun"
                placeholder="请输入来源地址"
                v-decorator="['consultRecord.keyWebsite', {rules: [{ required: false, message: '请选择来源地址！' }]}]"
              />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="6 " :sm="24" layout="vertical">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="预约时间"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-date-picker
                :disabled="disabled_zixun"
                :disabled-date="disabledDate"
                :show-time="{format:'HH:mm'}"
                format="YYYY-MM-DD HH:mm"
                placeholder="选择预约时间"
                style="width: 100%"
                v-decorator="['consultRecord.orderDate',
                {initialValue:(row_record.orderDate!=='-'||!row_record.orderDate)?moment(row_record.orderDate,'YYYY-MM-DD HH:mm'):null }]"
              />
            </a-form-item>
          </a-form>
        </a-col>

        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="客户搜索关键词"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                :disabled="disabled_zixun"
                placeholder="请输入客户搜索关键词"
                v-decorator="['consultRecord.keyWord', {rules: [{ required: false, message: '请输入客户搜索关键词！' }]}]"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="来源网站"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                :disabled="disabled_zixun"
                placeholder="请输入来源网站"
                v-decorator="['consultRecord.sourceWebsite', {rules: [{ required: false, message: '请输入来源网站！' }]}]"
              />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row type="flex" align="middle">
        <a-col :span="18">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="咨询内容"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-textarea
                :disabled="disabled_zixun"
                :rows="3"
                placeholder="请输入咨询内容"
                v-decorator="['consultRecord.consultCondition', {rules: [{ required: false, message: '请输入咨询内容！' }]}]"
              >
              </a-textarea>
            </a-form-item>
          </a-form>
        </a-col>
<!--        <a-col :span="5" :offset="1">-->
<!--          <a-button @click="submit" type="primary" style="width: 100px;" >提交</a-button>-->
<!--        </a-col>-->
      </a-row>
      <!--用户模块弹出窗，待优化抽离-->
      <a-modal
        :footer="null"
        title="双击选择客户"
        :width="800"
        :visible="visibleTable"
        @cancel="visibleTable=false"
      >
        <a-table
          :alert="true"
          :columns="columns"
          :data-source="customerDataTable"
          :loading="customerTableLoading"
          :pagination="pagination"
          :rowKey="(record,index)=>index"
          @change="handleTableChange"
          :customRow="click"
        >
        </a-table>

      </a-modal>
    </a-modal>
  </div>

</template>

<script>
import {
  getConsulationListByTel,
  getConsultationAppeal,
  getCustomerInfo,
  updateNetConsultation
} from '@/api/modular/main/customer/customerConsultation'
import { AllHisUser, getCustomerConsult, getInfoSource } from '@/api/customer/customer'
import areaObj from '@/assets/flowable/js/areaData'
import infoSourceObj from '@/assets/flowable/js/infoSource'
import moment from 'moment'

export default {
  data(){
    return{
      row_record:{},
      customer_response: {
        developerid:undefined,
        consult_man_id:undefined
      },
      value: [],
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      sex:[{'id':'0','name':'男'},{'id':'1','name':'女'}],
      area: areaObj.areaData,//区域
      infoSource: [],//消息来源
      CustomerConsult: { //客户咨询下拉系列
        comeHosStatus : [], //来院意向
        consultTools : [],//咨询工具
        contactDetails : [],//联系方式
      },
      userList:[],
      //客户诉求列表
      ConsultationAppeal : [],
      disabled:true,
      disabled_zixun:false,
      disabled_search:false,
      disabled_name:false,
      disabled_card:false,
      disabled_tel:false,
      disabled_age:true,
      disabled_info_source:true,
      disabled_area_source:true,
      visible: false,
      visibleTable: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      customerTableLoading:false,
      pagination: {
        current: 1,//当前页
        pageSize: 10,//当前页数
        total: 0,//总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'],//这里注意只能是字符串，不能是数字
        showTotal: total => `共有 ${ total} 条数据`,//分页中显示总的数据
      },
      customerDataTable:[],
      columns: [
        { title: '序号', customRender: (text, record, index)=>(this.pagination.current-1)*this.pagination.pageSize+(index+1) },
        { title: '姓名', dataIndex: 'name' },
        { title: '卡号', dataIndex: 'cardNo' },
        { title: '开发员', dataIndex: 'developer', customRender:age=>age?age:'无' },
        { title: '咨询师', dataIndex:'consultMan', customRender:consultMan=>{return consultMan?consultMan:'无'} },
        { title: '登记时间', dataIndex: 'recordDate', }
      ],
    }
  },
  created() {
    this.getInfoSource()
    this.getCustomerConsult()
    this.getConsultationAppeal()
    this.AllHisUser()
  },
  methods:{
    moment,
    /**
     不可选择日期
     * */
    disabledDate(current) {
      // return current
      return current < moment().add(-1, 'd')
    },
    filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },
    // 初始化方法
    add (row_record) {
      this.row_record=row_record
      this.visible = true
      this.confirmLoading = false
      this.disabled_search=false
      this.disabled_area_source=true
      this.disabled_info_source=true
      this.disabled_age=true
      this.disabled=true
      this.form.resetFields()
      this.$nextTick(()=>{
        this.$refs.phoneInput.focus()
        console.log('点击行编辑',this.row_record)
        const customerInfo=this.row_record
        this.customer_response.developerid=this.row_record.developer_id
        this.customer_response.consult_man_id=this.row_record.consultMan
        this.form.setFieldsValue({
          'consultRecord.consultToolId':customerInfo.consultToolId,
          'consultRecord.keyWord':customerInfo. keyWord,
          'consultRecord.keyWebsite':customerInfo.keyWebsite,
          'consultRecord.sourceWebsite':customerInfo.sourceWebsite,
          'consultRecord.consultCondition':customerInfo.consultCondition,
          'consultRecord.clientIntentionId':customerInfo.clientIntentionId,
          'quoteItemList':Array.from(new Set(customerInfo.consultItemIdList)) ,
          'customer.age': customerInfo.age,
          'customer.name': customerInfo.name,
          'customer.cardNo': customerInfo.card_no,
          'customer.areaId': customerInfo.area_id===0?undefined: areaObj.getAreaId(customerInfo.area_id),
          'customer.infoSource':customerInfo.infoSource_id===0?undefined: infoSourceObj.getinfoSourceId( this.infoSource,customerInfo.infoSource_id),
          'customer.sex':customerInfo.sex==1?'女':(customerInfo.sex==0?'男':undefined),
          'customerContact.contactType':customerInfo.contact_type,
          'customerContact.contactContent':customerInfo.contact_content,
        })
      })
    },
    /**
     表单校验手机号格式
     * */
    validatorPhone (rule, value, callback) {
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!reg.test(value)) {
        callback('11位')
      }
      callback()
    },
    /**
     员工接口
     * */
    AllHisUser(){
      AllHisUser().then(res => {
        this.userList = res.userList
      })
    },
    /**
     表单校验年龄
     * */
    validatorAge (rule, value, callback) {
      if(!value){
        callback()
      }
      if(value>0&&value<100){
        callback()
      }
      callback('年龄必须为1-99')
    },
    /**
     请求信息来源
     * */
    getInfoSource(){
      getInfoSource().then(res => {
        this.infoSource = res
      })
    },
    /**
     下拉接口集合
     * */
    getCustomerConsult(){
      getCustomerConsult().then(res => {
        this.CustomerConsult = res
      })
    },
    getConsultationAppeal(){
      getConsultationAppeal().then(res => {
        this.ConsultationAppeal = res.data
      })
    },
    /**
     判断渲染表格
     * */
    resToRender(res){
      if(res.code==200){
        //搜索不到用户
        if(res.rows.length<=0){
          this.$message.info({
            content:'该客户不存在',
            duration:1,
          })
          this.disabled=false
          this.disabled_zixun=false
          this.disabled_age=false
          this.disabled_info_source=false
          this.disabled_area_source=false
        }else if(res.rows.length==1){
          //搜索到一条数据，直接渲染，需要选择点击
          this.getCustomerInfoAndRender(res.rows[0].customerId)
        }else{
          //搜索到用户数据两条以上
          this.visibleTable=true
          this.customerDataTable=res.rows
        }
      }
    },
    /**
     查询客户
     * */
    searchCustomer(type){
      const tel =this.form.getFieldValue('customerContact.contactContent')
      if(type=='tel'){
        this.form.resetFields()
        this.form.setFieldsValue({
          'customerContact.contactContent':  tel,
        })
        getConsulationListByTel(tel).then(res=>{
          this.resToRender(res)
          this.confirmLoading = false
        })
      }
    },
    /**
     提交表单
     * */
    submit(){
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        this.confirmLoading = true
        if (errors) {
          console.log('表单检验未通过111',errors,values)
          this.confirmLoading = false
          return
        }
        values.consultRecord.orderDate = moment(values.consultRecord.orderDate).format('YYYY-MM-DD HH:mm:ss')
        if(values.customer.infoSource&&values.customer.infoSource?.length>0){
          values.customer.infoSource=values.customer.infoSource[1]
        }else{
          values.customer.infoSource=this.customer_response.info_source
        }

        if(values.customer.areaId&&values.customer.areaId?.length>0){
          values.customer.areaId=values.customer.areaId[2]
        }else{
          values.customer.areaId=this.customer_response.area_id
        }
        if(values.customer.sex){
          values.customer.sex = values.customer.sex ==='女'?1:(values.customer.sex==1?1:0)
          values.customer.sex = values.customer.sex ==='男'?0:(values.customer.sex==1?1:0)
        }

        if(this.customer_response){
          values.customer.customerId=this.customer_response.customerId
        }
        console.log('表单检验通过222',values)
        const updateValues={
          sex: values.customer.sex,
          age: values.customer.age,
          quoteItemList:values.quoteItemList,
          consultRecordId	:this.row_record.consultId,
          customerId	:this.row_record.customerId,
          consultDate:this.row_record.consultDate,
          consultCondition	:values.consultRecord.consultCondition,
          clientIntention	:values.consultRecord.clientIntentionId,
          orderDate	:values.consultRecord.orderDate,
          consultTool	:values.consultRecord.consultToolId,
          keyWord	:values.consultRecord.keyWord,
          keyWebsite	:values.consultRecord.keyWebsite,
          sourceWebsite	:values.consultRecord.sourceWebsite,
        }
        updateNetConsultation(updateValues).then(res =>{
          console.log('提交结果为',res)
          if(res.code==200){
            this.$message.success({
              content:'修改成功',
              duration:1,
              onClose:()=>{
                this.visible=false
                this.$emit('reLoadDerailsNet')
                this.confirmLoading = false
              }
            })
          }else{
            this.$message.info({
              content:res.message,
              duration:1,
              onClose:()=>{
                this.confirmLoading = false
              }
            })
          }

        })
      })
    },
    /**
     分页动作监听
     * */
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      this.getList()
    },
    /**
     表格行点击事件
     * */
    click(record, index){
      return {
        on: {
          dblclick:()=>{
            const customerId = record.customerId
            this.getCustomerInfoAndRender(customerId)
          }
        }
      }
    },
    handleCancel () {
      this.form.resetFields()
      this.visible = false
    },
    /**
     请求用户资料数据并且渲染页面
     * */
    getCustomerInfoAndRender(customerId){
      getCustomerInfo(customerId).then(res=>{
        console.log('客户信息',res)
        if(res.code==200){
          const customerInfo = res.data
          this.customer_response=res.data
          this.form.setFieldsValue({
            'customer.age': customerInfo.age,
            'customer.name': customerInfo.name,
            'customer.cardNo': customerInfo.card_no,
            'customer.areaId': customerInfo.area_id===0?undefined: areaObj.getAreaId(customerInfo.area_id),
            'customer.infoSource':customerInfo.info_source===0?undefined: infoSourceObj.getinfoSourceId( this.infoSource,customerInfo.info_source),
            'customer.sex':customerInfo.sex==1?'女':'男',
            'customerContact.contactType':customerInfo.contact_type,
            'customerContact.contactContent':customerInfo.contact_content,
          })
          this.visibleTable=false
          if(!customerInfo.age||customerInfo.age<0||customerInfo.age>99){
            this.disabled_age=false
          }
          this.disabled_area_source=(customerInfo.area_id==0||!customerInfo.area_id)?false:true
          this.disabled_info_source=(customerInfo.info_source==0||!customerInfo.info_source)?false:true
          this.disabled_search=true
          this.disabled_zixun=false
        }else{
          this.$message.info({
            content:res.message,
            duration:1,
            onClose:()=>{
              this.visibleTable=false
            }
          })
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-head-title{
  font-weight: bold;
}
/deep/ .ant-page-header-heading-title{
  font-weight: normal;
  font-size: 16px;
}
/deep/ .ant-card-body {
  padding: 24px 12px 0;
}
/deep/ .ant-form-item-control-wrapper{
  width: 100%;
}
/deep/ .ant-form-item{
  margin-bottom: 6px;
}
</style>